var FY = {
    isMobile: function(){
        return /(mobile|iphone|ipad|android|phone|meego|rim|blackberry)/i.test(navigator.userAgent);
    },
    isAndroid: function(){
        return /android/i.test(navigator.userAgent);
    },
    isIOS: function(){
        return /(phone|iphone|ipad)/i.test(navigator.userAgent);
    },
    assert: function(condition, msg){
        if(!condition){
            throw new Error('FY:' + msg);
        }
    },
    /**
     * 获取url的参数
     * @function
     * @param {String} [name] 不传值则返回所有参数组成的object
     * @param {String} [url] 需要解析的链接，不填默认是location.href
     * @returns {String|Object}
     * @example
     */
    getUrlParam: function(name, url){
        var str = (url || location.href), index = str.indexOf('?'), n, arr = [], returnObj = {};
        if(index != -1){
            str = str.substring(index + 1);
            arr = str.split('#')[0].split('&');
        }
        for(n = 0; n < arr.length; ++n){
            arr[n] = arr[n].split('=');
            returnObj[arr[n][0]] = returnObj[arr[n][0].toLowerCase()] = (arr[n][1] || '');
        }
        return name ? returnObj[name] : returnObj;
    },
    reportJsError: function(msg, url, line, level, type){
        typeof maya != 'undefined' && maya.report(msg, url, line, 4, type);
        //上报kb2
        var url = window.FY_HOST.manageUrl + '/common/report/jsalarm?msg='+msg+'&url='+url+'&rd='+Math.random();
        var img = new Image();
        img.onload = img.onerror = function () {
            img = null;
        };
        img.src = url;
    },
    loadScript: function(url, callback){
        var script = document.createElement("script");
        script.type = "text/javascript";
        if(script.readyState){ //IE
            script.onreadystatechange = function(){
                if(script.readyState == "loaded" ||
                    script.readyState == "complete"){
                    script.onreadystatechange = null;
                    callback && callback();
                }
            };
        }else{ //Others: Firefox, Safari, Chrome, and Opera
            script.onload = function(){
                callback && callback();
            };
        }
        script.src = url;
        document.body.appendChild(script);
    },
    loadCSS: function(url){
        var cssLink = document.createElement("link");
        cssLink.rel = "stylesheet";
        cssLink.rev = "stylesheet";
        cssLink.type = "text/css";
        cssLink.media = "screen";
        cssLink.href = url;
        document.getElementsByTagName("head")[0].appendChild(cssLink);
    },
    //initMqqOpenUrl : function(){
    //    var _that = this;
    //    //文本组件的超链接 链接组件 按钮组件
    //    $('body').delegate('.v-paragraph-style a,v-href-style a,.v-button-style,.v-caption-style', 'click', function(e){
    //        var url = $(this).attr('href');
    //        if(mqq && mqq.ui && url.indexOf('www.')>-1){
    //            mqq.ui.openUrl({
    //                url: url,
    //                target: 1,
    //                style: 3
    //            });
    //            e.preventDefault();
    //        }
    //    });
    //},
    /**
     * 初始化组件
     */
    initModules: {
        /**
         * 初始化表单
         */
        initForm: function(){
            FY.loadScript('/static/region.js?isAdvanced=1&v=' + window.__version, function(){
                FY.loadScript('/static/weui/weui.js?isAdvanced=1&v=' + window.__version, function(){
                    FY.loadScript('/static/region.js?isAdvanced=1&v=' + window.__version, function(){
                        FY.loadScript('/admaker/widgets/Form/formpage.js?isAdvanced=1&v=' + window.__version, function(){
                            if(typeof FormComponent == 'undefined'){
                                FY.reportJsError('FormComponent.js加载失败','',0,4,2);
                            }else{
                                $(".VAct_form").each(function(){
                                    var render_id = $(this).attr('render_id');
                                    var form_info_id = $(this).attr('form_info_id');
                                    var form_id = $(this).attr('form_id');
                                    var p_id = $(this).attr('p_id');
                                    var success_link = $(this).attr('success_link');
                                    var success_info = $(this).attr('success_info');
                                    var single_commit = $(this).attr('single_commit');
                                    var is_jump = $(this).attr('is_jump');
                                    var open_sms_verify = $(this).attr('open_sms_verify');
                                    var open_success_info = $(this).attr('open_success_info');
                                    var open_captcha = $(this).attr('open_captcha');
                                    var open_auto_city = $(this).attr('open_auto_city');
                                    FormComponent.init(render_id, form_info_id, form_id, p_id, {
                                        'success_link': success_link,
                                        'success_info': success_info,
                                        'single_commit': single_commit,
                                        'is_jump': is_jump,
                                        'open_sms_verify' : open_sms_verify,
                                        'open_success_info' : open_success_info,
                                        'open_captcha' : open_captcha,
                                        'open_auto_city' : open_auto_city
                                    });
                                })
                            }
                        })
                    })
                })
            });
        },
        /**
         * 初始化地图
         */
        initMap: function(){
            window.qq = window.qq || {};
            qq.maps = qq.maps || {};
            window.soso || (window.soso = qq);
            soso.maps || (soso.maps = qq.maps);

            var loadScriptTime = (new Date).getTime();

            qq.maps.__load = function(apiLoad){
                delete qq.maps.__load;
                apiLoad([["2.4.58", "", 0], ["open.map.qq.com/", "apifiles/2/4/58/mods/", "open.map.qq.com/apifiles/2/4/58/theme/", true], [1, 18, 34.519469, 104.461761, 4], [1494571805665, "pr.map.qq.com/pingd", "pr.map.qq.com/pingd"], ["apis.map.qq.com/jsapi", "apikey.map.qq.com/mkey/index.php/mkey/check", "sv.map.qq.com/xf", "sv.map.qq.com/boundinfo", "sv.map.qq.com/rarp", "apis.map.qq.com/api/proxy/search", "apis.map.qq.com/api/proxy/routes/", "confinfo.map.qq.com/confinfo"], [[null, ["rt0.map.gtimg.com/tile", "rt1.map.gtimg.com/tile", "rt2.map.gtimg.com/tile", "rt3.map.gtimg.com/tile"], "png", [256, 256], 1, 19, "114", true, false], [null, ["m0.map.gtimg.com/hwap", "m1.map.gtimg.com/hwap", "m2.map.gtimg.com/hwap", "m3.map.gtimg.com/hwap"], "png", [128, 128], 4, 18, "110", false, false], [null, ["p0.map.gtimg.com/sateTiles", "p1.map.gtimg.com/sateTiles", "p2.map.gtimg.com/sateTiles", "p3.map.gtimg.com/sateTiles"], "jpg", [256, 256], 1, 19, "101", false, false], [null, ["rt0.map.gtimg.com/tile", "rt1.map.gtimg.com/tile", "rt2.map.gtimg.com/tile", "rt3.map.gtimg.com/tile"], "png", [256, 256], 1, 19, "", false, false], [null, ["sv0.map.qq.com/hlrender/", "sv1.map.qq.com/hlrender/", "sv2.map.qq.com/hlrender/", "sv3.map.qq.com/hlrender/"], "png", [256, 256], 1, 19, "", false, false], [null, ["rtt2.map.qq.com/rtt/", "rtt2a.map.qq.com/rtt/", "rtt2b.map.qq.com/rtt/", "rtt2c.map.qq.com/rtt/"], "png", [256, 256], 1, 19, "", false, false], null, [["rt0.map.gtimg.com/vector/", "rt1.map.gtimg.com/vector/", "rt2.map.gtimg.com/vector/", "rt3.map.gtimg.com/vector/"], [256, 256], 4, 18, "114", ["rt0.map.gtimg.com/icons/", "rt1.map.gtimg.com/icons/", "rt2.map.gtimg.com/icons/", "rt3.map.gtimg.com/icons/"]], null], ["s.map.qq.com/TPano/v1.1.2/TPano.js", "map.qq.com/", ""]], loadScriptTime);
            };

            var src = "open.map.qq.com/apifiles/2/4/58/main.js",
                protocol = (window.location.protocol == "https:") ? "https://" : "http://";

            src = src && (src.indexOf("http://") === 0 || src.indexOf("https://") === 0) ? src : protocol + src;

            FY.loadScript(src, function(){
                $('.VAct_modelBox[data-map]').each(function(){
                    var map = $(this), lat = map.attr('data-lat'),
                        lng = map.attr('data-lng'), name = map.attr('data-name'),
                        address = map.attr('data-address'), zoom = parseInt(map.attr('data-zoom'));

                    var latLng = new qq.maps.LatLng(lat, lng);

                    var map = new qq.maps.Map(map.find('.map-container')[0], {
                        center: latLng,
                        mapTypeControl: false,
                        zoomControl: false,
                        panControl: false,
                        zoom: zoom
                    });

                    var infoWin = new qq.maps.InfoWindow({
                        map: map
                    });

                    var marker = new qq.maps.Marker({
                        map: map,
                        position: latLng
                    });

                    qq.maps.event.addListener(marker, 'click', function(){
                        infoWin.open();
                        infoWin.setContent('<div>' + name + '<a class="data-report" data-type="map" style="padding-left: 10px; color: #20a0ff" ' +
                            'href="http://apis.map.qq.com/uri/v1/marker?marker=coord:' + lat + ',' + lng + ';title:' + name + ';addr:' + address + '&referer=zhihuitui">详情>></a><br />地址：' + address + '</div>');
                        infoWin.setPosition(latLng);
                    });
                });
            });
        },
        /**
         * 初始化幻灯片
         */
        initGallery: function(){
            var galleries = $('.VAct_modelBox[data-gallery]');

            if(galleries.length && galleries.length != $('.v-gallery-default').length){ // v-gallery-default 为空白组件
                FY.loadScript('/static/landing/js/swiper.min.js?isAdvanced=1', function(){
                    galleries.each(function(){
                        var gallery = $(this), speed = parseInt(gallery.attr('data-speed'));

                        if(!gallery.find('.v-gallery-default').length){
                            new Swiper(gallery.find('.swiper-container')[0], {
                                autoplay: speed * 1000,
                                loop: true,
                                grabCursor: true,
                                setWrapperSize: true,
                                pagination: '.swiper-pagination',
                                paginationClickable: true,
                                autoplayDisableOnInteraction: false
                            });
                        }
                    });
                });
            }
        },
        /**
         * 微信卡券
         */
        initWxcard: function(){
            window.mod = {};
            window.GDTAD = {};
            window.callback_GDT_Card = function(mod){
                GDTAD.cardMod = mod;
            }
            function getURL(url) {
                return new Promise(function(resolve, reject) {
                    var script = document.createElement('script');
                    script.type = "text/javascript";
                    if (script.readyState){  //IE
                        script.onreadystatechange = function() {
                            if (script.readyState == "loaded" ||
                                script.readyState == "complete") {
                                script.onreadystatechange = null;
                                resolve('success: '+url);
                            }
                        };
                    } else {  //Others
                        script.onload = function(){
                            resolve('success: '+url);
                        };
                    }
                    script.onerror = function() {
                        reject(Error(url + 'load error!'));
                    };

                    script.src = url+'?'+'time='+Date.parse(new Date());
                    document.body.appendChild(script);

                });
            }
            $(".wxcard-lq").click(function(){
                var card_id = $(this).attr('card_id');
                $.ajax({
                    type: 'get',
                    dataType: 'json',
                    timeout : 8000,
                    url: '/wxcard/getsign?card_id='+card_id+"&isAdvanced=1",
                    success: function(result) {
                        if(result.code == 1){
                            var URL = "http://qzs.qq.com/gdt/display/busi_module/openCard.js";
                            getURL(URL).then(function(){
                                var info = {
                                    "id": card_id,
                                    "ext": '{"code": "", "openid": "", "timestamp": "'+result.data.timestamp+'", "signature":"'+result.data.signature+  '","nonce_str":"' + result.data.nonce_str + '"}'
                                }
                                try{
                                    GDTAD.cardMod && GDTAD.cardMod.addCardToWX && GDTAD.cardMod.addCardToWX(info, function(suc) {

                                    }, function(fail) {

                                    })
                                } catch (err) {

                                }
                            });
                        }
                    },
                    error: function() {

                    }
                });
            });
        },
        initVideo : function(){
            var _that = this;
            $('.video-modelBox').each(function(e){
                var id = $(this).attr('id');
                var vid = $(this).attr('vid');
                if(FY.isMobile()){
                    var width = window.screen.width;
                }else{
                    var width = 640;
                }
                var pic = $(this).attr('pic');

                //先临时修复下，视频不显示的问题
                var img = new Image();
                img.onload = function(){
                    _that.playVideo(id,vid,width,this.width,this.height,pic)
                };
                img.onerror = function(){
                    _that.playVideo(id,vid,width,640,498,pic)
                };
                img.src = pic;
            })
        },
        playVideo : function(id,vid,width,pixelwidth,pixelheight,pic){
            var video = new tvp.VideoInfo();
            video.setVid(vid);
            var player = new tvp.Player();
            if(vid != ''){
                player.create({
                    width: width,
                    height: Math.round(width * pixelheight / pixelwidth),
                    video: video,
                    modId: id,
                    autoplay: false,
                    pic: pic,
                    playerType: 'html5'
                });
            }
        },
        run: function(){
            if($(".VAct_form").length > 0){
                this.initForm();
            }

            if($('.VAct_modelBox[data-map]').length){
                this.initMap();
            }

            if($('.wxcard-modelBox').length){
                this.initWxcard();
            }
            var _that = this;
            if($('.video-modelBox').length){
                FY.loadScript('/static/tvp.player_v2.js?isAdvanced=1',function(){
                    _that.initVideo();
                })
            }
        }
    }
};